package com.yoyo.itravel.web.controller;

import com.yoyo.itravel.bean.Airline;
import com.yoyo.itravel.bean.JsonResult;
import com.yoyo.itravel.bean.PageBean;
import com.yoyo.itravel.exceptions.AirlineException;
import com.yoyo.itravel.service.IAirlineService;
import com.yoyo.itravel.utils.JSONUtils;
import com.yoyo.itravel.utils.StringUtils;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.lang3.RandomUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @author liuchaojie
 * @version 1.0
 * @Description 航空公司
 * @date 2020/6/19 10:37
 */
@Controller
@RequestMapping("/airline")
public class AirlineController {
    @Autowired
    private IAirlineService airlineService;

    @RequestMapping("/findAll")
    public void findAll(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        try {
            List<Airline> airlines = airlineService.selectAll();
            for (Airline airline: airlines){
                System.out.println(airline);
            }
            JSONUtils.writeValueToResponse(airlines, response);
        } catch (AirlineException e) {
            e.printStackTrace();
        }
    }


    @RequestMapping("/deleteByAirlineId")
    public void deleteByAirlineId(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        try {
            String airlineId = request.getParameter("airlineId");
            boolean flag = airlineService.deleteByAirlineId(airlineId);
            JSONUtils.writeValueToResponse(flag, response);
        } catch (AirlineException e) {
            e.printStackTrace();
        }
    }


    @RequestMapping("/findAirlineByPage")
    @ResponseBody
    protected JsonResult findAirlineByPage(Integer page, @RequestParam("limit") Integer size) throws ServletException, IOException {
        PageBean pageBean = new PageBean(page, size);
        JsonResult jsonResult = new JsonResult();
        List<Airline> list = null;
        try {
            list = airlineService.findAirlineByPage(pageBean);
            // 查询总数
            Integer totalCount = airlineService.totalCount();
            jsonResult.setData(list);
            jsonResult.setCode(0);
            jsonResult.setCount(totalCount);
        } catch (AirlineException e) {
            e.printStackTrace();
        }
        return jsonResult;
    }

    /**
     * 增加一个航空公司
     * @return
     */
    @RequestMapping(value = "addAirline")
    public void addAirline(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        try {
            String airlineId = request.getParameter("airlineId");
            String airlineName = request.getParameter("airlineName");
            String icon = request.getParameter("icon");
            String phone = request.getParameter("phone");
            String address = request.getParameter("address");
            String ontimeRate = request.getParameter("ontimeRate");
            String alipayUID = request.getParameter("alipayUID");
            String registerTime = request.getParameter("registerTime");
            String description = request.getParameter("description");
            Airline airline = new Airline();
            airline.setAirlineId(StringUtils.getRandomUUID());
            airline.setAirlineName(airlineName);
            airline.setIcon(icon);
            airline.setPhone(phone);
            airline.setAddress(address);
            airline.setOntimeRate(Double.parseDouble(ontimeRate));
            airline.setAlipayUID(alipayUID);
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            Date date = sdf.parse(registerTime);
            airline.setRegisterTime(date);
            airline.setDescription(description);
            boolean flag = airlineService.addAirline(airline);
            JSONUtils.writeValueToResponse(flag, response);
        } catch (AirlineException e) {
            e.printStackTrace();
        } catch (ParseException e) {
            e.printStackTrace();
        }
    }


    /**
     * 修改航空公司信息
     * @return
     */
    @RequestMapping("/changeAirline")
    @ResponseBody
    public void changeAirline(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        try {
            String airlineId = request.getParameter("airlineId");
            String airlineName = request.getParameter("airlineName");
            String icon = request.getParameter("icon");
            String phone = request.getParameter("phone");
            String address = request.getParameter("address");
            String ontimeRate = request.getParameter("ontimeRate");
            String alipayUID = request.getParameter("alipayUID");
            String registerTime = request.getParameter("registerTime");
            String description = request.getParameter("description");
            Airline airline = new Airline();
            airline.setAirlineId(airlineId);
            airline.setAirlineName(airlineName);
            airline.setIcon(icon);
            airline.setPhone(phone);
            airline.setAddress(address);
            airline.setOntimeRate(Double.parseDouble(ontimeRate));
            airline.setAlipayUID(alipayUID);
            Date date = new Date();
            date.setTime(Long.parseLong(registerTime));
            airline.setRegisterTime(date);
            airline.setDescription(description);
            System.out.println(airline);
            boolean flag = airlineService.changeAirline(airline);
            JSONUtils.writeValueToResponse(flag, response);
        } catch (AirlineException e) {
            e.printStackTrace();
        }
    }


    /**
     * 修改准点率
     * @param airlineId
     * @param ontimeRate
     * @return
     */
    @RequestMapping(value = "changeOnTimeRate", method = RequestMethod.POST)
    public ModelAndView changeOnTimeRate(String airlineId, Double ontimeRate){
        ModelAndView mav = new ModelAndView();
        try {
            boolean flag = airlineService.changeOnTimeRate(airlineId, ontimeRate);
            if(flag){
                mav.addObject("msg","准点率更新成功！");
                mav.setViewName("success");
            }else{
                mav.addObject("msg","准点率更新失败！");
                mav.setViewName("fail");
            }
        } catch (AirlineException e) {
            e.printStackTrace();
        }
        return mav;
    }

    @RequestMapping(value = "/icon", method = {RequestMethod.POST})
    @ResponseBody
    public Object iconImg(@RequestParam(value="file",required=false) MultipartFile attach, HttpServletRequest request, HttpServletResponse response) throws Exception {
        String carPictuerUrl = null;
        //判断文件是否为空
        if(!attach.isEmpty()){
            String path1 = request.getSession().getServletContext().getRealPath("/");
            String path = request.getSession().getServletContext().getRealPath("images/flight/icon");
            System.out.println("path1:==============="+path1);

            System.out.println("path======"+path);
            String contentType = attach.getContentType();
            System.out.println("contentType:"+contentType);
            String oldFileName = attach.getOriginalFilename();//原文件名
            System.out.println("oldFileName:"+oldFileName);
            String prefix = FilenameUtils.getExtension(oldFileName);//原文件后缀
            /**
             * RandomUtils.nextInt(1, 1000000)
             * 返回一个在指定区间内的整数
             * startInclusive 可以返回的最小值必须是非负的
             * endExclusive 上限（不包括）
             */
            String fileName = System.currentTimeMillis()+ RandomUtils.nextInt(1,1000000)+"."+prefix;
            File targetFile = new File(path, fileName);  //创建文件
            if(!targetFile.exists()){  //判断文件夹是否存在
                targetFile.mkdirs();
            }

            try {
                attach.transferTo(targetFile);
            } catch (IllegalStateException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
            carPictuerUrl = "images/flight/icon/"+fileName;
        }

        HashMap<String,Object> map2=new HashMap<String,Object>();
        HashMap<String,Object> map=new HashMap<String,Object>();
        map.put("code",0);
        map.put("msg","");
        map.put("data",map2);
        map2.put("src",carPictuerUrl);
        return map;
    }


}
